package com.example.listviewtest;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.w3c.dom.Text;

import java.util.List;

public class AppAdapter extends ArrayAdapter<AppItem> {

    private int resourceId;

    AppAdapter(@NonNull Context context, int textViewResourceId, @NonNull List<AppItem> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        AppItem appItem = getItem(position);
//        View view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);


        //进行优化，convertView用于将之前加载好的布局进行缓存，以便以后可以进行重用
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);

            //当convertView未进行缓存时，创建ViewHolder对象，并将控件的实例存放在其中
            //然后调用View的setTag()方法，将ViewHolder对象存储到View中
            viewHolder = new ViewHolder();
            viewHolder.appImage = view.findViewById(R.id.app_img);
            viewHolder.appName = view.findViewById(R.id.app_name);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            //当存在convertView缓存时，将View中的ViewHolder对象取出
            viewHolder = (ViewHolder) view.getTag();
        }

//        改进前
//        ImageView appImage = view.findViewById(R.id.app_img);
//        TextView appName = view.findViewById(R.id.app_name);
//        appImage.setImageResource(appItem.getImageId());
//        appName.setText(appItem.getName());

        //改进后
        assert appItem != null;
        viewHolder.appImage.setImageResource(appItem.getImageId());
        viewHolder.appName.setText(appItem.getName());

        return view;
    }

    class ViewHolder {
        //利用ViewHolder来改善findViewById()的频繁调用带来的消耗
        ImageView appImage;
        TextView appName;
    }
}
